import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtFloatLayout, AtForm, AtIcon, AtInput} from "taro-ui";
import {View, ScrollView} from '@tarojs/components'
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import {GetRequest, vcmonitor} from "../../../utils/tools";
import {
  INVOICE_GET_ORDER_TITLE_DETAIL, INVOICE_ORDER_INVOICE_DETAIL, INVOICE_ORDER_SAVE,
  INVOICE_ORDER_TITLE_PAGE, INVOICE_ORDER_UPDATE, TARO_ENV
} from "../../../constants/api";
import {http} from "../../../utils/http";
import RadioGrounp from "../../productForm/components/radio-gounp";
import './invoice.scss'

interface StateType {
  info: any
  lookUpList: any
  showFloat: any
  headType: any
}

export default class Invoice extends Component {
  state: StateType = {
    showFloat: false,
    info: {
      invoicetitle_name: '',
      invoicetitle_type: 0,
      unit_id_number: '',
      order_num: '',
      address: '',
      phone: '',
      bank: '',
      bank_account: ''
    },
    lookUpList: [],
    headType: [{label: '个人或事业单位', value: 0}, {label: '企业', value: 1}]
  }

  async UNSAFE_componentWillMount() {
    this.orderNum = Taro.getCurrentInstance().router.params.orderNum || ''
    this.isUpdate = Taro.getCurrentInstance().router.params.isUpdate || ''
    let {info} = this.state
    info['order_num'] = this.orderNum
    if (!this.isUpdate){
      const data = await http.HGet(INVOICE_GET_ORDER_TITLE_DETAIL, {})
      if (data) {
        info = this.jiaoji(info, data.data)
      }
    }
    if (this.isUpdate){
      const data = await http.HGet(INVOICE_ORDER_INVOICE_DETAIL, {order_num: this.orderNum})
      if (data) {
        info = this.jiaoji(info, data.data)
      }
    }
    this.setState({info})
  }

  async componentDidShow() {
    vcmonitor(this)
    this.isUpdate = Taro.getCurrentInstance().router.params.isUpdate || ''
    if (!this.isUpdate){
      const res = await http.HGet(INVOICE_ORDER_TITLE_PAGE, {})
      if (JSON.stringify(res) !== '{}') {
        this.setState({lookUpList: res.data})
      }
    }
  }

  orderNum
  isUpdate

  jiaoji(a, b) {
    const c = {}
    for (const item in a) {
      if (b[item] !== undefined && b[item] !== null) {
        c[item] = b[item]
      } else {
        c[item] = a[item]
      }
    }
    return c
  }

  async confirmRequest() {
    const that = this
    Taro.showModal({
      title: '提示',
      cancelText: '返回修改',
      confirmText: '提交审核',
      content: '请确认信息无误再提交！',
      success: async function (res) {
        if(res.confirm){
          const params = Object.assign({}, that.state.info)
          let api = INVOICE_ORDER_SAVE
          if (that.isUpdate){
            api = INVOICE_ORDER_UPDATE
          }
          const res = await http.HPost(api, params)
          if (res) {
            Taro.showToast({title: !that.isUpdate ? '保存成功' : '修改成功', duration: 2000})
            setTimeout(() => {
              let mpkey = ''
              const uInfo = Taro.getStorageSync('user') || ''
              if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
                mpkey = uInfo.mpkey
              }
              Taro.redirectTo({
                url: '/main/order/invoice/invoice-detail?orderNum=' + that.orderNum + '&mpkey=' + mpkey
              })
            }, 2000)
          }
        }
      }
    })
  }

  handleChange(field, val) {
    if(field === 'invoicetitle_type') {
      let form = {
        invoicetitle_name: '',
        invoicetitle_type: 0,
        order_num: this.orderNum
      }
      if (val) {
        form = {
          invoicetitle_name: '',
          invoicetitle_type: 1,
          unit_id_number: '',
          order_num: this.orderNum,
          address: '',
          phone: '',
          bank: '',
          bank_account: ''
        }
      }
      let data
      if (this.state.lookUpList && this.state.lookUpList.length > 0) {
        const index = this.state.lookUpList.findIndex(item => { return item.invoicetitle_type === val })
        if (index > -1) {
          data = this.state.lookUpList[index]
        }
      }
      if (data) {
        form = this.jiaoji(form, data)
      }
      this.setState({info: form})
    } else {
      const {info} = this.state
      info[field] = val
      this.setState({info})
    }
  }


  changeLookUp(item) {
    let form = {
      invoicetitle_name: '',
      invoicetitle_type: 0,
      order_num: this.orderNum
    }
    if (item.invoicetitle_type) {
      form = {
        invoicetitle_name: '',
        invoicetitle_type: 1,
        unit_id_number: '',
        order_num: this.orderNum,
        address: '',
        phone: '',
        bank: '',
        bank_account: ''
      }
    }
    form = this.jiaoji(form, item)
    this.setState({info: form, showFloat: false})
  }

  render() {
    const {info, headType, showFloat, lookUpList} = this.state
    return (
      <View className='Invoice-Information-order'>
        <GzhAuth />
        <AtForm>
          <View className='form-wrapper'>
            <AtInput disabled title='发票类型' type='text' value='普通发票' />
            <View className='check_radio_wrapper check_radio_wrapper-loop-up-type'>
              <View className={`business-form-block-item-left ${TARO_ENV + 'business-form-block-item-left'}`}>
                抬头类型
              </View>
              <View>
                <RadioGrounp
                  onChange={({value}) => this.handleChange('invoicetitle_type', value)}
                  data={headType}
                  wNo
                  iconSize='20'
                  scrollWrap
                  isCheck={info.invoicetitle_type}
                  size='14px'
                />
              </View>
            </View>
            <AtInput
              name='unit_id_number'
              title='发票抬头'
              type='text'
              className='icon-chevron-right'
              placeholder='填写需要开具发票的姓名'
              value={info.invoicetitle_name}
              onChange={this.handleChange.bind(this, 'invoicetitle_name')}
            ><AtIcon  onClick={() => {this.setState({showFloat: true})}} value='chevron-right' size='16' color='#999' /></AtInput>
            {!!info.invoicetitle_type && <View>
              <AtInput
                name='unit_id_number'
                title='税号'
                type='text'
                placeholder='请输入税号'
                value={info.unit_id_number}
                onChange={this.handleChange.bind(this, 'unit_id_number')}
              />
              <AtInput
                name='bank'
                title='开户银行'
                type='text'
                placeholder='选填'
                value={info.bank}
                onChange={this.handleChange.bind(this, 'bank')}
              />
              <AtInput
                name='bank_account'
                title='银行账号'
                type='text'
                placeholder='选填'
                value={info.bank_account}
                onChange={this.handleChange.bind(this, 'bank_account')}
              />
              <AtInput
                name='address'
                title='企业地址'
                type='text'
                placeholder='选填'
                value={info.address}
                onChange={this.handleChange.bind(this, 'address')}
              />
              <AtInput
                name='phone'
                title='企业电话'
                type='text'
                placeholder='选填'
                value={info.phone}
                onChange={this.handleChange.bind(this, 'phone')}
              />
            </View>}
          </View>
        </AtForm>
        <View className='confirm-invoice' onClick={this.confirmRequest.bind(this)}>提交申请</View>
        {showFloat && <AtFloatLayout isOpened={showFloat} title='抬头选择' onClose={() => {
          this.setState({showFloat: false})
        }}
        >
          <ScrollView enable-flex scrollY className='scroll-view'>
            <View className='scroll'>
              {lookUpList.map(item => {
                return <View className='look-up-item' key={item.id}
                  onClick={this.changeLookUp.bind(this, item)}
                >
                  <View className='left-content'>
                    <View className='left-title'>{item.invoicetitle_name}</View>
                    <View className='left-look-up'>{item.type}</View>
                  </View>
                  <View className='right-content'>
                    <View onClick={() => {
                      Taro.navigateTo({url: `/main/order/invoice/look-up-detail?id=${item.id}`})
                    }}
                    >详情</View>
                    <View className='line'>|</View>
                    <View onClick={() => {
                      Taro.navigateTo({url: `/main/order/invoice/addLookUp?id=${item.id}`})
                    }}
                    >编辑</View>
                  </View>
                </View>
              })}
              {lookUpList.length <= 0 && <View style='text-align: center; margin-top: 50%;'>暂无数据</View>}
            </View>
          </ScrollView>
          <View className='add-new-look-up' onClick={() => {
            Taro.navigateTo({url: '/main/order/invoice/addLookUp'})
          }}
          >添加新抬头</View>
        </AtFloatLayout>
        }
      </View>
    )
  }
}
